<template>
   <div style="height: 600px;">
      <!-- 动态查询 -->
      <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
         <el-form-item label="课程名称" prop="subjectName">
            <el-input v-model="queryParams.subjectName" placeholder="请输入课程名称" clearable style="width: 220px"
               @keyup.enter="handleQuery" />
         </el-form-item>

         <el-form-item label="阶段名称" prop="levelId">
            <el-select v-model="queryParams.levelId" placeholder="请选择阶段名称" clearable style="width: 220px"
               @keyup.enter="handleQuery">
               <el-option v-for="item in options" :key="item.id" :label="item.levelName" :value="item.id" />
            </el-select>
         </el-form-item>
         <el-form-item label="学习阶段" prop="lpId">
            <el-select v-model="queryParams.lpId" placeholder="请选择学习阶段名称" clearable style="width: 220px">
               <el-option v-for="dict in options1" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
               v-hasPermi="['system:role:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
               v-hasPermi="['system:role:edit']">修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
               v-hasPermi="['system:role:remove']">删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
               v-hasPermi="['system:role:export']">导出</el-button>
         </el-col>
         <el-row style="margin-left: 65%;">
            <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top"
               v-if="search">
               <el-button circle icon="Search" @click="toggleSearch()" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="刷新" placement="top">
               <el-button circle icon="Refresh" @click="refresh()" />
            </el-tooltip>
         </el-row>
      </el-row>

      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="filterTableData" @selection-change="handleSelectionChange"
         :header-cell-style="{ background: '#eee', color: '#909399' }">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="课程编号" prop="id" width="263" />
         <el-table-column label="阶段名称" prop="slevel.levelName" :show-overflow-tooltip="true" width="263" />
         <el-table-column label="学习阶段名称" prop="slearningProgress.name" :show-overflow-tooltip="true" width="263" />
         <el-table-column label="课程名称" prop="subjectName" :show-overflow-tooltip="true" width="263" />
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:role:edit']"></el-button>
               </el-tooltip>
               <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:role:remove']"></el-button>
               </el-tooltip>
               <el-tooltip content="查看题目" placement="top">
                  <el-button link type="primary" icon="View" @click="handleAuthUser(scope.row)"
                     v-hasPermi="['system:role:edit']"></el-button>
               </el-tooltip>
            </template>
         </el-table-column>
      </el-table>
   </div>
   <el-pagination background v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 15, 20, 25]" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />

   <!-- 添加或修改角色配置对话框 -->
   <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
         <el-form-item label="阶段名称" prop="levelId">
            <el-select v-model="form.levelId" placeholder="请选择阶段名称" clearable style="width: 220px"
               @change="byId(form.levelId)">
               <el-option v-for="item in options" :key="item.id" :label="item.levelName" :value="item.id" />
            </el-select>
         </el-form-item>

         <el-form-item label="学习阶段" prop="lpId">
            <el-select v-model="form.lpId" placeholder="请选择学习阶段名称" clearable style="width: 220px">
               <el-option v-for="dict in options2" :key="dict.id" :label="dict.name" :value="dict.id" />
               <template #empty >
                  <span style="color: red;">请先选择一个阶段哦~</span>
               </template>
            </el-select>
         </el-form-item>

         <el-form-item label="课程名称" prop="subjectName">
            <el-input v-model="form.subjectName" placeholder="请输入课程名称" />
         </el-form-item>
      </el-form>
      <template #footer>
         <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
         </div>
      </template>
   </el-dialog>
   <!-- 查看题目 -->
   <el-dialog v-model="dialogVisible" title="题目预览" width="800" :before-close="handleClose" :fullscreen="true">
      <div ref="containerRef"
         style="width: 79%;height: 635px;display: inline-block;overflow-y: auto;-ms-overflow-style: none;scrollbar-width: none;overflow: scroll;">
         <el-card :id="'part' + item.id" v-for="(item, index) in optionsQuestion"
            :body-style="{ padding: item.typeId == 3 || item.typeId == 4 ? '0px' : '20px' }"
            style="margin-bottom: 15px;">
            <template #header>
               <div class="card-header">
                  <span style="display: inline-block;width: 950px;">{{ index + 1 + ". " +
                     item.question.split("/")[0] }}</span>
                  <span style="position: relative;right: 0px;">{{ "("+(item.typeId==1?'单选题':item.typeId==2?'多选题':item.typeId==3?'判断题':item.typeId==4?'简答题':null)+" ) "
                     }}</span>
               </div>
            </template>
            <p style="margin-top: 10px;" v-if="item.typeId == 1"
               :style="{ color: item.answerTxt == 'A' && i == 0 ? 'red' : item.answerTxt == 'B' && i == 1 ? 'red' : item.answerTxt == 'C' && i == 2 ? 'red' : item.answerTxt == 'D' && i == 3 ? 'red' : 'BLACK' }"
               v-for="(text, i) in item.question.split('/')[1].split('_')" class="text item">{{ text }}</p>
            <p v-if="item.typeId == 2" :style="{ color: getColor(item.answerTxt, i) ? 'red' : 'black' }"
               v-for="(text, i) in item.question.split('/')[1].split('_')" class="text item">{{ text }}</p>
            <template #footer>答案：<span :style="{ color: item.typeId == 3 && item.answerTxt ? 'green' : 'red' }">{{
               item.answerTxt
            }}</span></template>
         </el-card>
      </div>
      <div
         style="width: 20%;display: inline-block;height: 635px;overflow-y: auto;-ms-overflow-style: none;scrollbar-width: none;overflow: scroll;">
         <el-anchor style="height: 600px;" :container="containerRef" direction="vertical" type="horizontal"
            :offset="238" @click="handleClick">
            <el-anchor-link v-for="(item, index) in optionsQuestion" style="size: 20px;" :href="'#part' + item.id"
               :title="index + 1 + '.' + item.question.split('/')[0]" />
         </el-anchor>
      </div>
   </el-dialog>

</template>

<script setup>
import { adminSubjectList, adminLevelList, adminLearningProgressList, adminSubjectAdd, adminSubjectById, adminSubjectUpdate, adminSubjectDelete, exportOrder, adminLevelById, adminQuestionBySubjectId } from "@/api/admin/subject/index.js";
import { ref, onMounted, getCurrentInstance, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
const { proxy } = getCurrentInstance();

const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const options = ref([])
const options1 = ref([])
const options2 = ref([])
const optionsQuestion = ref([])
const dialogVisible = ref(false)

//讲师表单
let form = ref({
   id: '',
   levelId: '',
   lpId: '',
   subjectName: ''
})

//动态查询
const queryParams = ref({
   pageNum: 1,
   pageSize: 10,
   subjectName: '',
   levelId: '',
   lpId: ''
})
//分页
const handleSizeChange = (val) => {
   queryParams.value.pageSize = val
   getList()
}
const handleCurrentChange = (val) => {
   queryParams.value.pageNum = val
   getList()
}
onMounted(() => {
   getList();
   getShow();
   getSelect();
})
const rules = reactive({
   levelId: [{ required: true, message: '阶段不能为空', trigger: 'blur' }],
   subjectName: [{ required: true, message: '课程名称不能为空', trigger: 'blur' }],
   lpId: [{ required: true, message: '学习阶段不能为空', trigger: 'blur' }]
})
//根据阶段id查找具体专业几
function byId(id) {
   adminLevelById(id).then(res => {
      if (res.data.code == 200) {
         options2.value = res.data.obj
      }
   })
}
/** 查询课程列表 */
function getList() {
   loading.value = true;
   adminSubjectList(queryParams.value).then(response => {
      // 假设后端返回了一个格式为 "01:00:00" 的时间字符串
      let dbTime = "01:00:00";
      let time = new Date("1970-01-01T" + dbTime + "Z");  // 构造一个日期对象

      // 使用toLocaleTimeString方法将时间转换为本地时间格式
      let formattedTime = time.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
      roleList.value = response.data.obj.records;
      total.value = response.data.obj.total;
      loading.value = false;
   });
}
//查询单元名称
const filterTableData = computed(() =>
   roleList.value.filter(
      (data) =>
         !queryParams.value.subjectName ||
         data.subjectName.toLowerCase().includes(queryParams.value.subjectName.toLowerCase()),
   )
)
// 查询班级列表
function getShow() {
   adminLevelList().then(res => {
      if (res.data.code == 200) {
         options.value = res.data.obj
      }
   })
}
//查询学习阶段
function getSelect() {
   adminLearningProgressList().then(res => {
      if (res.data.code == 200) {
         options1.value = res.data.obj
      }
   })
}
/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   queryParams.value.levelId = '';
   queryParams.value.subjectName = '';
   queryParams.value.lpId = '';
   handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
   if (ids.value.length > 0) {
      ids.value.forEach(arr => {
         adminSubjectDelete(arr).then(res => {
         })
      });
      getList()
      ElMessage.success('删除成功')
   } else {
      ElMessageBox.confirm(
         '您确认要删除课程编号为' + row.id + '的数据项?',
         '温馨提示',
         {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
         }).then(() => {
            adminSubjectDelete(row.id).then(res => {
               if (res.data.code == 200) {
                  ElMessage.success('删除成功')
                  ids.value = []
                  getList()
               } else {
                  ElMessage.error(res.data.message)
               }
            })
         })
         .catch(() => {
            ElMessage({
               type: 'info',
               message: '已取消删除',
            })
         })
   }
}
/** 导出按钮操作 */
function handleExport() {
   exportOrder().then(res => {
      const xlsx = "application/vnd.ms-excel";
      const blob = new Blob([res.data], { type: xlsx });
      const a = document.createElement("a");
      let fileName = "课程信息" + new Date().getTime() + ".xlsx";
      a.download = fileName;
      a.href = window.URL.createObjectURL(blob)
      a.click()
      a.remove()
   });
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
   ids.value = []
   selection.forEach(arr => {
      ids.value.push(arr.id)
   });
   single.value = selection.length != 1;
   multiple.value = !selection.length;
}

/** 重置新增的表单以及其他数据  */
function reset() {
   form.value = {
      id: undefined,
      levelId: undefined,
      subjectName: undefined,
      lpId: undefined,
   };
}
/** 添加课程 */
function handleAdd() {
   reset();
   open.value = true;
   title.value = "添加课程";
}
/** 修改课程 */
function handleUpdate(row) {
   const uid = ref(row.id);
   const id = ref(0);
   ids.value.forEach(arr => {
      id.value = arr
   });
   if (id.value != 0) {
      uid.value = id.value
   }
   reset();
   adminSubjectById(uid.value).then(response => {
      byId(response.data.obj.levelId)
      form.value = response.data.obj;
      form.value.id = response.data.obj.id
      open.value = true;
      title.value = "修改课程";
   });
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
         if (form.value.id != undefined) {
            adminSubjectUpdate(form.value).then(response => {
               ElMessage.success("修改成功");
               open.value = false;
               getList();
            });
         } else {
            adminSubjectAdd(form.value).then(response => {
               if (response.data.code == 200) {
                  ElMessage.success("新增成功");
                  open.value = false;
                  getList();
               } else {
                  ElMessage.error(response.data.message)
                  open.value = false;
                  getList();
               }
            });
         }
      }
   });
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}

// 根据课程id查找对应的题目信息
function handleAuthUser(row) {
   dialogVisible.value = true
   adminQuestionBySubjectId(row.id).then(res => {
      if (res.data.code == 200) {
         optionsQuestion.value = res.data.obj
      }
   })
}
const getColor = (text, i) => {
   var boo = false
   text.split("").forEach(element => {
      if (element == "A" && i == 0 || element == "B" && i == 1 || element == "C" && i == 2 || element == "D" && i == 3) {
         boo = true
      }
   });
   return boo
}
const props = defineProps({
   /* 是否显示检索条件 */
   showSearch: {
      type: Boolean,
      default: true,
   },
   /* 显隐列信息 */
   columns: {
      type: Array,
   },
   /* 是否显示检索图标 */
   search: {
      type: Boolean,
      default: true,
   },
   /* 显隐列类型（transfer穿梭框、checkbox复选框） */
   showColumnsType: {
      type: String,
      default: "checkbox",
   },
   /* 右外边距 */
   gutter: {
      type: Number,
      default: 10,
   },
})

const emits = defineEmits(['update:showSearch', 'queryTable']);

// 搜索
function toggleSearch() {
   if (showSearch.value == true) {
      showSearch.value = false
   } else {
      showSearch.value = true
   }
   emits("update:showSearch", !props.showSearch);
}

// 刷新
function refresh() {
   getList()
}
</script>
<style>
.avatar-uploader .el-upload {
   border: 1px dashed var(--el-border-color);
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
   transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
   border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
   font-size: 28px;
   color: #8c939d;
   width: 178px;
   height: 178px;
   text-align: center;
}

/* main-container全局样式 */
.app-container {
   padding: 20px;
}

label {
   font-weight: 700;
}
</style>